package com.ssy.lingxi.open.api.controller;

import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.component.redis.service.IRedisUtils;
import com.ssy.lingxi.open.api.entity.User;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 公共入口类
 * @author jw.chen
 * @version 2.0.0
 * @date @date 2021/10/13
 */
public class ApiBaseController {

    @Resource
    private IRedisUtils redisUtils;

    @Resource
    private HttpServletRequest request;

    /**
     * 判断用户是否已登录
     * @return 登录-true，未登录-false
     */
    public Boolean isLogin() {
        String token = request.getHeader(Constants.TOKEN);
        if (StringUtils.hasLength(token)) {
            Object obj = redisUtils.get(token, Constants.REDIS_OPEN_API_INDEX);
            return obj != null;
        }
        return false;
    }

    /**
     * 判断用户是否已登录，如未登录抛出异常，由各个服务的异常拦截器进行处理
     */
    public void checkLogin() {
        String token = request.getHeader(Constants.TOKEN);
        if(!StringUtils.hasLength(token) || Objects.isNull(redisUtils.get(token, Constants.REDIS_OPEN_API_INDEX))) {
            throw new BusinessException(ResponseCode.TOKEN_DOES_NOT_EXIST_IN_CACHE);
        }
    }

    /**
     * 获取登录用户信息
     * @return Redis缓存中的登录用户信息
     */
    public User getUser() {
        String token = request.getHeader(Constants.TOKEN);
        if (StringUtils.hasLength(token)) {
            Object obj = redisUtils.get(token, Constants.REDIS_OPEN_API_INDEX);
            if (obj != null) {
                return JSONUtil.parse(obj).toBean(User.class);
            } else {
                throw new BusinessException(ResponseCode.TOKEN_DOES_NOT_EXIST_IN_CACHE);
            }
        } else {
            throw new BusinessException(ResponseCode.TOKEN_DOES_NOT_EXIST_IN_CACHE);
        }
    }

}
